package com.reremouse.rerebbs.dao.impl;

import com.reremouse.rerebbs.dao.IBbsFileDAO;
import com.reremouse.rerebbs.dao.IBbsUserDAO;
import com.reremouse.rerebbs.dao.ISystemConfigDAO;
import com.reremouse.rerebbs.model.BbsFileModel;
import com.reremouse.rerebbs.model.FileSaveStatus;
import org.apache.commons.io.IOUtils;

import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletContext;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class BbsFileDAOImpl
        implements IBbsFileDAO {
    @PersistenceContext
    private EntityManager entityManager;
    IBbsUserDAO cu;
    ISystemConfigDAO timesNumDAO;
    String relativeFilePath = "/resources/sys/file/";

    public EntityManager getEntityManager() {
        return this.entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public String getRelativeFilePath() {
        return this.relativeFilePath;
    }

    public void setTimesNumDAO(ISystemConfigDAO timesNumDAO) {
        this.timesNumDAO = timesNumDAO;
    }

    public IBbsUserDAO getCu() {
        return this.cu;
    }

    public void setCu(IBbsUserDAO cu) {
        this.cu = cu;
    }

    public void delClientFile(long id) {
        BbsFileModel cf = (BbsFileModel) this.entityManager.find(BbsFileModel.class, Long.valueOf(id));
        delFile(id);
        this.entityManager.remove(cf);
    }

    public boolean checkNameIfExist(String name, long fid) {
        String q = "Select fs from BbsFileModel fs where fs.fileName='" + name + "' AND fs.fatherID=" + fid;

        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        if (ais.isEmpty()) {
            return false;
        }
        return true;
    }

    public List<BbsFileModel> findAllClientFile() {
        String q = "Select fs from BbsFileModel fs order by fs.uploadTime desc";
        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        for (BbsFileModel p : ais) {
            p.setUser(this.cu.findBbsUser(p.getUser_id()));
            List t = findAllSonClientFile(p.getId());
            if (t != null) {
                p.setSonNum(t.size());
            }
        }
        return ais;
    }

    public List<BbsFileModel> findAllSonClientFile(long dic) {
        String q = "Select fs from BbsFileModel fs where fs.fatherID=" + dic + " order by fs.uploadTime desc";

        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        for (BbsFileModel p : ais) {
            p.setUser(this.cu.findBbsUser(p.getUser_id()));
            List t = findAllSonClientFile(p.getId());
            if (t != null) {
                p.setSonNum(t.size());
            }
        }
        return ais;
    }

    public List<BbsFileModel> findAllSonDirsByUsr(long dic, long uid) {
        String q = "Select fs from BbsFileModel fs where fs.fatherID=" + dic + " and fs.user_id=" + uid + " and fs.ifFolder=true order by fs.uploadTime desc";

        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        for (BbsFileModel p : ais) {
            p.setUser(this.cu.findBbsUser(p.getUser_id()));
            List t = findAllSonClientFile(p.getId());
            if (t != null) {
                p.setSonNum(t.size());
            }
        }
        return ais;
    }

    public List<BbsFileModel> findAllClientFileByUsr(long uid, long dic) {
        String q = "Select fs from BbsFileModel fs where fs.user_id=" + uid + " and fs.fatherID=" + dic + " order by fs.uploadTime desc";

        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        for (BbsFileModel p : ais) {
            p.setUser(this.cu.findBbsUser(p.getUser_id()));
            List t = findAllSonClientFile(p.getId());
            if (t != null) {
                p.setSonNum(t.size());
            }
        }
        return ais;
    }

    public List<BbsFileModel> findAllClientFileByUsr(long uid) {
        String q = "Select fs from BbsFileModel fs where fs.user_id=" + uid + " order by fs.uploadTime desc";
        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        for (BbsFileModel p : ais) {
            p.setUser(this.cu.findBbsUser(p.getUser_id()));
            List t = findAllSonClientFile(p.getId());
            if (t != null) {
                p.setSonNum(t.size());
            }
        }
        return ais;
    }

    public BbsFileModel findClientFile(long id) {
        BbsFileModel s = (BbsFileModel) this.entityManager.find(BbsFileModel.class, Long.valueOf(id));
        if (s != null) {
            s.setUser(this.cu.findBbsUser(s.getUser_id()));
            List t = findAllSonClientFile(s.getId());
            if (t != null) {
                s.setSonNum(t.size());
            }
        }
        return s;
    }

    public void saveClientFileInfo(BbsFileModel s) {
        if (s.getUser() != null) {
            s.setUser_id(s.getUser().getId().longValue());
        }
        this.entityManager.persist(s);
    }

    public void updateClientFileInfo(BbsFileModel s) {
        if (s.getUser() != null) {
            s.setUser_id(s.getUser().getId().longValue());
        }
        this.entityManager.merge(s);
    }

    public List<BbsFileModel> searchClientFile(String field, String keyWords) {
        String q = "Select fs from BbsFileModel fs where fs." + field + " LIKE '%" + keyWords + "%' order by ps.uploadTime desc";

        List<BbsFileModel> ais = this.entityManager.createQuery(q).getResultList();
        for (BbsFileModel p : ais) {
            p.setUser(this.cu.findBbsUser(p.getUser_id()));
            List t = findAllSonClientFile(p.getId());
            if (t != null) {
                p.setSonNum(t.size());
            }
        }
        return ais;
    }

    private boolean testIfAncestorByDB(BbsFileModel son, long target) {
        long fatherId = son.getFatherID();
        if ("0".equals(Long.valueOf(target))) {
            return true;
        }
        if (fatherId == target) {
            return true;
        }
        if (fatherId == 0L) {
            return false;
        }
        testIfAncestorByDB(findClientFile(fatherId), target);

        return false;
    }

    private boolean testIfContain(BbsFileModel c, List<BbsFileModel> ffs) {
        if (c == null) {
            return false;
        }
        boolean t1 = false;
        for (BbsFileModel fc : ffs) {
            if (fc.getId() == c.getId()) {
                t1 = true;
                break;
            }
        }
        return t1;
    }

    public void saveFile(InputStream iis, long id, long userId) {
        try {
            byte[] bb = new byte[1024];
            InputStream fis = iis;
            String dir = "";
            boolean f = this.timesNumDAO.getSystemConfig().getIfRelative().booleanValue();
            if (f) {
                String tp = this.timesNumDAO.getSystemConfig().getFilePath();
                if (!tp.endsWith("/")) {
                    tp = tp + "/";
                }
                dir = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath(tp);
            } else {
                dir = this.timesNumDAO.getSystemConfig().getFilePath();
            }
            if (!dir.endsWith("\\")) {
                dir = dir + "\\";
            }
            File f_dir = new File(dir);
            if (!f_dir.exists()) {
                f_dir.mkdir();
            }
            System.out.println("store path:" + dir);

            String rp = dir + userId;
            File f_rp = new File(rp);
            if (!f_rp.exists()) {
                f_rp.mkdir();
            }
            String nfn = rp + "\\" + id;
            FileOutputStream fos = new FileOutputStream(nfn);


            BufferedInputStream is = new BufferedInputStream(fis);
            BufferedOutputStream os = new BufferedOutputStream(fos);


            IOUtils.copy(is, os);
            os.flush();

            is.close();
            os.close();
            fis.close();

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveFile(InputStream iis, long id, long userId, FileSaveStatus stat) {
        stat.setSaving(true);
        try {
            byte[] bb = new byte[1024];
            InputStream fis = iis;
            String dir = "";
            boolean f = this.timesNumDAO.getSystemConfig().getIfRelative().booleanValue();
            if (f) {
                String tp = this.timesNumDAO.getSystemConfig().getFilePath();
                if (!tp.endsWith("/")) {
                    tp = tp + "/";
                }
                dir = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath(tp);
            } else {
                dir = this.timesNumDAO.getSystemConfig().getFilePath();
            }
            if (!dir.endsWith("\\")) {
                dir = dir + "\\";
            }
            File f_dir = new File(dir);
            if (!f_dir.exists()) {
                f_dir.mkdir();
            }
            System.out.println("store path:" + dir);

            String rp = dir + userId;
            File f_rp = new File(rp);
            if (!f_rp.exists()) {
                f_rp.mkdir();
            }
            String nfn = rp + "\\" + id;
            FileOutputStream fos = new FileOutputStream(nfn);
            BufferedInputStream is = new BufferedInputStream(fis);
            BufferedOutputStream os = new BufferedOutputStream(fos);
            int len = 0;
            while ((len = is.read(bb)) != -1) {
                os.write(bb, 0, len);
                stat.setReaded(stat.getReaded() + len);
            }
            os.flush();
            is.close();
            os.close();
            fis.close();

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        stat.setSaving(false);
    }

    private void delFile(long id) {
        long group = findClientFile(id).getUser().getId().longValue();
        String dir = "";
        boolean f = this.timesNumDAO.getSystemConfig().getIfRelative().booleanValue();
        if (f) {
            String tp = this.timesNumDAO.getSystemConfig().getFilePath();
            if (!tp.endsWith("/")) {
                tp = tp + "/";
            }
            dir = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath(tp);
        } else {
            dir = this.timesNumDAO.getSystemConfig().getFilePath();
        }
        if (!dir.endsWith("\\")) {
            dir = dir + "\\";
        }
        String rp = dir + group;
        String nfn = rp + "\\" + id;
        File f1 = new File(nfn);
        if (f1.exists()) {
            f1.delete();
        }
    }

    public void delClientFilebyUsr(long userId) {
        String sql = "delete from BbsFileModel uls where uls.user_id=" + userId;
        this.entityManager.createQuery(sql).executeUpdate();
    }

    public void delClientFileAndAllDescendants(long id) {
        List<BbsFileModel> sons = new ArrayList();
        loadAllDescendants(id, sons);
        delClientFile(id);
        for (BbsFileModel s : sons) {
            delClientFile(s.getId());
        }
    }

    public List<BbsFileModel> loadAllDescendants(long fid) {
        List<BbsFileModel> sons = new ArrayList();
        loadAllDescendants(fid, sons);
        return sons;
    }

    public void loadAllDescendants(long fid, List<BbsFileModel> sons) {
        List<BbsFileModel> ls = findAllSonClientFile(fid);
        if (ls.isEmpty()) {
            return;
        }
        for (BbsFileModel d : ls) {
            sons.add(d);
            loadAllDescendants(d.getId(), sons);
        }
    }
}



/* Location:           F:\jsp源码\蝙蝠论坛系统\rerebbs\WEB-INF\classes\

 * Qualified Name:     com.reremouse.rerebbs.dao.impl.BbsFileDAOImpl

 * JD-Core Version:    0.7.0.1

 */